import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {GovinfosService} from "./govinfos.service";
import {ResponseUtil} from "../../../util/response-util";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {MsgResult} from "../../../models/msg-result";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {API, MsgConstants} from "../../../constants/constants";
import {TableUtil} from "../../../util/table-util";

declare var $;

@Component({
  selector: 'app-govinfos',
  templateUrl: './govinfos.component.html'
})
export class GovinfosComponent implements OnInit,AfterViewInit {

  @ViewChild(OneOperationComponent) operation: OneOperationComponent;


  //定义id变量
  id:Array<string> = [];

  table;
  treeObj;

  constructor(
    private router :Router,
    private route : ActivatedRoute,
    private pageSubject : PageSubject,
    private tableUtil : TableUtil,
    private responseUtil : ResponseUtil,
    private dialogService : OneDialogService,
    private govInfosService : GovinfosService
  ) { }

  proxy = {
    "govInfoAdd": () => this.govInfoAdd(),
    "govInfoDelete": () => this.govInfoDelete(),
    "govInfoUpdate": () => this.govInfoUpdate()
  }

  ngOnInit() {

    this.pushPage();

    this.loadGovInfo();

    this.administrativeDivisionTree();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("政府管理","查询",path);
  }

  //添加政府机构
  govInfoAdd(){
    this.router.navigate(['add'],{relativeTo : this.route});
  }

  //删除弹窗

  govInfoDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    this.id=this.tableUtil.getIds(rows);
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }
  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
      this.govInfosService.deleteGovInfo(this.id[0]).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
  }
  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  search() {
    this.table.bootstrapTable('refresh');
  }

  //修改政府机构
  govInfoUpdate(){
    let rows = this.table.bootstrapTable('getSelections');
    this.id=this.tableUtil.getIds(rows);
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['update', {govId: this.id[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 获取行政区划树
   */
  administrativeDivisionTree() {
    this.govInfosService.getRetrieveRegionsTree().subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //初始化zTree
      this.regioCodezTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  regioCodezTree(data){
    //    zTreee
    let setting = {
      callback: {
        onClick: this.clickTree
      }
    };

    let zNodes =data;

    this.treeObj = $.fn.zTree.init($("#government_ZTree"), setting, zNodes);
  }
  clickTree = (event, treeId, treeNode) =>{
    let govId = $("#gov_Id");
    if(treeNode.id == govId.val()){
      let selectedArray:Array<Object> = this.treeObj.getSelectedNodes();
      if (selectedArray.length>0) {
        this.treeObj.cancelSelectedNode(selectedArray[0]);
      }
      govId.val("");
    }else{
      govId.val(treeNode.id);
    }
    this.search();
  };

  /**
   * 政府列表查询
   */
  loadGovInfo() {
    this.table = this.tableUtil.load("one_table_gov",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "name", title: '名称', align: 'left'},
        {field: "regionName", title: '行政区划', align: 'left'},
        {field: "phone", title: '联系方式', align: 'right'},
        {field: "isValid", title: '有效', align: 'left', formatter: this.yesOrNoFormat},
        {field: "isDisable", title: '禁用', align: 'left', formatter: this.yesOrNoFormat},
        {field: "creatorName", title: '创建人', align: 'left',visible: false},
        {field: "create_date", title: '创建日期', align: 'left',sortName:'CREATE_DATE',sortable:true ,visible: false},
        {field: "updatorName", title: '修改人', align: 'left',visible: false},
        {field: "update_date", title: '修改日期', align: 'left',visible: false,sortName:'UPDATE_DATE',sortable:true}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_govinfos",
      url: API.govPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#government").val();
        params.regionCode = $("#gov_Id").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.create_date = value.createDate || '';
            value.update_date = value.updateDate || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName:"CREATE_DATE",
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }
  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }
}
